//
//  LLBadgeButton.m
//  images
//
//  Created by ZDTX on 2018/2/7.
//  Copyright © 2018年 ZDTX. All rights reserved.
//

#import "LLBadgeButton.h"

#define LLBadgeColor [UIColor colorWithHexString:@"#F74A3D" alpha:1.0f]

@interface LLBadgeButton ()

@property (strong, nonatomic) UILabel *badgeLabel;

@end

@implementation LLBadgeButton

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        self.badgeLabel = [[UILabel alloc] init];
        self.badgeLabel.backgroundColor = LLBadgeColor;
        self.badgeLabel.font = [UIFont systemFontOfSize:10];
        self.badgeLabel.clipsToBounds = YES;
        self.badgeLabel.textAlignment = NSTextAlignmentCenter;
        self.badgeLabel.textColor = [UIColor whiteColor];
        [self addSubview:self.badgeLabel];
    }
    return self;
}

- (void)setBadgeValue:(NSInteger)badgeValue
{
    _badgeValue = badgeValue;
    [self setupText];
    [self setupSubviews];
}

- (void)setBadgeColor:(UIColor *)badgeColor
{
    _badgeColor = badgeColor;
    self.badgeLabel.backgroundColor = badgeColor;
}

- (void)setShowBadgeDot:(BOOL)showBadgeDot
{
    _showBadgeDot = showBadgeDot;
    self.badgeLabel.hidden = !showBadgeDot;
    if (showBadgeDot)
    {
        [self setupText];
        [self setupSubviews];
    }
}

- (void)setupText
{
    if (self.showBadgeDot)
    {
        self.badgeLabel.text = @"";
    }
    else
    {
        if (self.badgeValue <= 0)
        {
            self.badgeLabel.hidden = YES;
        }
        else
        {
            self.badgeLabel.hidden = NO;
            if (self.badgeValue > 99)
            {
                self.badgeLabel.text = @"99+";
            }
            else
            {
                self.badgeLabel.text = [NSString stringWithFormat:@"%ld",self.badgeValue];
            }
        }
    }
}

- (void)setupSubviews
{
    CGFloat badgeW;
    CGFloat badgeH;
    
    if (self.showBadgeDot)
    {
        badgeW = badgeH = 8;
    }
    else
    {
        badgeH = 15;
        badgeW = [self.badgeLabel sizeThatFits:CGSizeMake(MAXFLOAT, badgeH)].width+6;
        if (badgeW > 40)
        {
            badgeW = 40;
        }
        if (badgeW < badgeH)
        {
            badgeW = badgeH;
        }
    }
    
    self.badgeLabel.frame = CGRectMake(0, 0, badgeW, badgeH);
    if (self.imageView.image)
    {
        CGPoint center = CGPointMake(CGRectGetMaxX(self.imageView.frame)+10, self.imageView.bounds.origin.y);
        self.badgeLabel.center = center;
    }
    else
    {
        CGPoint center = CGPointMake(self.titleLabel.bounds.size.width + 10, self.titleLabel.frame.origin.y);
        self.badgeLabel.center = center;
    }
    self.badgeLabel.layer.cornerRadius = badgeH/2;
}


@end


